# -*- coding: utf-8 -*-

import os
import markdown2

def convert_markdown_to_html(input_file, output_file=None):
    # 读取Markdown文件内容
    with open(input_file, 'r', encoding='utf-8') as f:
        markdown_content = f.read()

    # 将Markdown转换为HTML
    html_content = markdown2.markdown(markdown_content)

    # 如果没有指定输出文件，则使用输入文件的名称并将扩展名更改为.html
    if output_file is None:
        output_file = os.path.join('public', os.path.splitext(os.path.basename(input_file))[0] + '.html')

    # 将HTML内容写入输出文件
    with open(output_file, 'w', encoding='utf-8') as f:
        # 添加HTML文档结构和<meta>标签指定字符集
        f.write('<!DOCTYPE html>\n<html>\n<head>\n<meta charset="utf-8">\n</head>\n<body>\n')
        f.write(html_content)
        f.write('\n</body>\n</html>')

if __name__ == "__main__":
    # 将pages目录下的所有Markdown文件转换为HTML，输出到public目录
    input_directory = os.path.join(os.getcwd(), 'src/pages')
    output_directory = os.path.join(os.getcwd(), 'public')

    markdown_files = [file for file in os.listdir(input_directory) if file.endswith('.md')]

    for markdown_file in markdown_files:
        input_path = os.path.join(input_directory, markdown_file)
        output_path = os.path.join(output_directory, os.path.splitext(os.path.basename(markdown_file))[0] + '.html')

        convert_markdown_to_html(input_path, output_path)
        print(f"Conversion completed: {markdown_file} -> {os.path.splitext(markdown_file)[0]}.html")
